<?php
include 'autoload.php';

$id = $_GET['id'];
$library = $_GET['library'];

if ( $id )
{
    $lib = new weebUILibrary( $library );
    $sql = $lib->query( "SELECT item_image, item_location FROM items WHERE item_id='$id'" );
    $data = sqlite_fetch_array( $sql );
    $filename = $data['item_image'];
    // # If the image is inside mp3, try to find image in folder!
    if ( substr( $filename, 0, 5 ) == "apic:" )
    {
        $dir = dirname( $data['item_location'] );
        $h = opendir( $dir );
        while ( $file = readdir( $h ) )
        {
            if ( ( $file != "." ) && ( $file != ".." ) )
            {
                $ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
                if ( !in_array( 'jpg', "jpeg", "gif", "png", "bmp" ) )
                    throw new weebUIUnsupportedFileExtensionException( $file, $supportedExtensions );
                else
                    $filename = "$dir\\$file";
            }
        }
    }

    list( $width, $height ) = getimagesize( $filename );

    if ( $width > 400 )
    {
        $dif = ( $width / $height );

        if ( $dif > 1 )
        {
            $w = 400;
            $h = ( $w / $dif );
        }elseif ( $dif < 1 )
        {
            $h = 400;
            $w = ( $h * $dif );
        }
        else
        {
            $w = 400;
            $h = 400;
        }
    }
    else
    {
        $w = $width;
        $h = $height;
    }

    $pic = imagecreatetruecolor( $w, $h );

    if ( exif_imagetype( $filename ) == 1 )
    {
        $source = imagecreatefromgif( $filename );
        header( 'Content-type: image/jpeg' );
    }
    if ( exif_imagetype( $filename ) == 2 )
    {
        $source = imagecreatefromjpeg( $filename );
        header( 'Content-type: image/gif' );
    }
    if ( exif_imagetype( $filename ) == 3 )
    {
        $source = imagecreatefrompng( $filename );
        header( 'Content-type: image/png' );
    }
    if ( exif_imagetype( $filename ) == 6 )
    {
        $source = imagecreatefromwbmp( $filename );
        header( 'Content-type: image/bmp' );
    }

    imagecopyresized( $pic, $source, 0, 0, 0, 0, $w, $h, $width, $height );
    imagejpeg( $pic );
}

else
{
    echo "image-id missing";
}